package com.woniuxy.woniubookmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.woniubookmanager.entity.UrlPermission;
import com.woniuxy.woniubookmanager.mapper.UrlPermissionMapper;
import com.woniuxy.woniubookmanager.service.UrlPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.woniubookmanager.vo.PermissionMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 菜单和接口权限定义 服务实现类
 * </p>
 *
 * @author wugd
 * @since 2022-11-29 04:03:13
 */
@Service
public class UrlPermissionServiceImpl extends ServiceImpl<UrlPermissionMapper, UrlPermission> implements UrlPermissionService {

    @Autowired
    UrlPermissionMapper urlPermissionMapper ;

    @Override
    public List<PermissionMenu> getAllMenu() {
        return urlPermissionMapper.selectAllMenu();
    }

    @Override
    public Page<UrlPermission> getPermissionByPage(Integer now, Integer size, String pname) {
        Page<UrlPermission> page = new Page<>(now,size);
        QueryWrapper<UrlPermission> queryWrapper = new QueryWrapper<>();
        if (pname != null && !pname.trim().equals("")){
            queryWrapper.like("name",pname);
        }
        Page<UrlPermission> urlPermissionPage = urlPermissionMapper.selectPage(page, queryWrapper);
        return urlPermissionPage;
    }

    @Override
    public List<PermissionMenu> getParentMenu() {
        List<PermissionMenu> urlPermissions = urlPermissionMapper.selectParentMenu();
        return urlPermissions;
    }

    @Override
    @Transactional
    public void removePermissionById(Long id) {
        //1. 判断 是子菜单 还是 父菜单
        UrlPermission urlPermission = urlPermissionMapper.selectById(id);
        if (urlPermission.getParentId() == -1){
            //先删除 子菜单 在删除 父菜单
            List<UrlPermission> list = urlPermissionMapper.selectPermissionByParentId(id);
            if (list != null && list.size() > 0 ){
                for (UrlPermission p : list) {
                    urlPermissionMapper.deletePermisisonAndRoleOfRelation(p.getId());
                    urlPermissionMapper.deleteById(p.getId());
                }
            }
        }else  {
            // 先删除关联关系
            urlPermissionMapper.deletePermisisonAndRoleOfRelation(id);
        }
        urlPermissionMapper.deleteById(id);
    }

    @Override
    public Long[] getPermissionIdByRoleId(Long id) {
        Long[] pids = urlPermissionMapper.selectPermissionIdByRoleId(id);
        return pids;
    }

    @Override
    public List<PermissionMenu> getPermissionMenuByUsername(String name) {
        return urlPermissionMapper.selectPermissionMenuByUsername(name);
    }
}
